#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/30 10:36
# @Author  : Samge
import json
from multiprocessing import Process

import requests
from PyQt5.QtCore import QDate

from itkz import token_util
from itkz.controls import crawls
from itkz.controls.base import BaseLogQueueControl
from itkz.resources.utils import config_util, tip_util


class ItkzControl(BaseLogQueueControl):

    sql_list = []

    def __init__(self, gui):
        super().__init__(gui)
        self.gui.itkz_db.set_log_queue(self.log_queue)

    def get_log_widget(self):
        return self.gui.tv_log

    def init_config_value(self):
        """
        复显配置
        :return:
        """
        self.init_cb_list(self.gui.cb_sql, self.sql_list, 'sql_list_value')
        self.gui.et_account.setText(config_util.value(f"{self.name()}/et_account_value", ''))
        self.gui.et_pw.setText(config_util.value(f"{self.name()}/et_pw_value", ''))
        self.gui.et_token.setText(config_util.value(f"{self.name()}/et_token_value", ''))
        self.gui.et_batch.setText(config_util.value(f"{self.name()}/et_batch_value", '1'))
        date_splits = config_util.value(f"{self.name()}/et_date_start_value", '2021-08-01').split('-')
        self.gui.et_date_start.setDate(QDate(int(date_splits[0]), int(date_splits[1]), int(date_splits[2])))
        self.gui.cb_need_update.setChecked(config_util.value(f"{self.name()}/need_update_value") == 'true')
        self.cb_status.init_config_value()

    def save_config_value(self):
        """
        保存当前选中的配置信息
        :return:
        """
        # 处理下拉选择框
        self.save_cb_list(self.gui.cb_sql, self.sql_list, 'sql_list_value')
        config_util.setValue(f"{self.name()}/et_account_value", self.gui.et_account.text())
        config_util.setValue(f"{self.name()}/et_pw_value", self.gui.et_pw.text())
        config_util.setValue(f"{self.name()}/et_token_value", self.gui.et_token.text())
        config_util.setValue(f"{self.name()}/et_batch_value", self.gui.et_batch.text())
        config_util.setValue(f"{self.name()}/et_date_start_value", self.gui.et_date_start.dateTime().toString('yyyy-MM-dd'))
        config_util.setValue(f"{self.name()}/need_update_value", self.gui.cb_need_update.isChecked())
        self.cb_status.save_config_value()

    def parse_spider(self, bt, bt_default_text):
        """
        处理爬虫抓取事件
        :param bt: 当前点击的按钮
        :param bt_default_text: 按钮默认显示的文本
        :return:
        """
        if bt.text() == bt_default_text:
            self.show_tv_log()

            is_crawl_list = bt == self.gui.bt_crawl_list
            spider_path = 'itkz.spiders.itkz.ItkzSpider' if is_crawl_list else 'itkz.spiders.itkz_baiduwangpan.ItkzBdSpider'

            date_start_str = self.gui.et_date_start.dateTime().toString('yyyy-MM-dd')
            if is_crawl_list and not date_start_str:
                tip_util.show_tip(self.gui, '请先正确配置【起始时间】')
                return

            token = self.gui.et_token.text()
            if not is_crawl_list and not token:
                tip_util.show_tip(self.gui, '请先正确配置【Token】信息')
                return

            self.save_config_value()
            self.reset_status()
            self.log_thread.start()
            bt.setText('停止爬取')

            spider_data = {
                'NEED_UPDATE': self.gui.cb_need_update.isChecked(),
                'use_proxy': self.cb_status.use_proxy(),
                'use_agent': self.cb_status.use_agent(),
                'use_splash': self.cb_status.use_splash(),
                'spider_path': spider_path,
                'TOKEN': token,
                'ACCOUNT': self.gui.et_account.text() or '',
                'PASSWORD': self.gui.et_pw.text() or '',
                'DATE_START_STR': date_start_str,
                'BATCH': int(self.gui.et_batch.text() or '1'),
            }
            # self.process = crawls.default_crawl(self.log_queue, spider_data)
            self.process = Process(target=crawls.default_crawl, args=(self.log_queue, spider_data))
            self.process.start()
            self.log_queue.put('爬虫开始')
        else:
            self.terminate(self.process)
            self.terminate(self.log_thread)
            bt.setText(bt_default_text)
            self.printLog("已手动结束爬虫")

    def onSpiderClose(self):
        super().onSpiderClose()
        self.gui.bt_crawl_list.setText(self.gui.BT_TEXT_CRAWL_LIST)
        self.gui.bt_crawl_bd.setText(self.gui.BT_TEXT_CRAWL_BD)

    def release(self):
        """ 释放资源 """
        super().release()
        self.sql_list = None

    def parse_baiduwangpan(self):
        pass

    def get_token(self):
        """
        获取登录后的token信息
        :return:
        """
        try:
            if self.gui.et_token.text():
                tip_util.show_tip(self.gui, "当前Token不为空，不需要重复获取")
                return

            account = self.gui.et_account.text()
            password = self.gui.et_pw.text()
            token = token_util.get_token(account, password)
            if token:
                self.save_config_value()
                requests.get(f"https://www.itkz.net/api/check_token?token={token}")
                tip_util.show_tip(self.gui, f"获取token成功【{token}】")
                self.gui.et_token.setText(token)
                self.save_config_value()
        except Exception as e:
            print(f"获取token失败 itkz_control 【{e}】")
            tip_util.show_tip(self.gui, f"获取token失败【{e}】")

    def printLog(self, v):
        super().printLog(v)
        if v.startswith("成功更新token："):
            self.gui.et_token.setText(v.split('：')[1])
            self.save_config_value()

    def show_tv_log(self):
        self.gui.tv_log.setVisible(True)
        self.gui.tableWidget.setVisible(False)

    def show_tableWidget(self):
        self.gui.tv_log.setVisible(False)
        self.gui.tableWidget.setVisible(True)
